<?php

namespace App\Http\Controllers\Adm\Member;

use App\Libs\WeChat\WxSmallClient;
use App\Models\goods_attr_val;
use App\Models\member;
use App\Models\order_goods;
use App\Models\order_info;
use App\Models\user;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class MemberController extends Controller
{


    /**
     * 会员管理
     */
    public function memberList(Request $request)
    {
        $ktime = !empty($request->input('ktime')) ? ($request->input('ktime')) : 0;
        $gtime = !empty($request->input('gtime')) ? ($request->input('gtime')) : 0;
        $phone = $request->input('phone','');
        $status = $request->input('status','');
        $user_type = $request->input('user_type','');
        if($ktime==$gtime &&  $ktime){
            $ktime = date("Y-m-d H:i:s",strtotime($ktime));
            $gtime = date("Y-m-d H:i:s",(strtotime($ktime)+86400));
        }
        $where = [];
        if($user_type) $where['phone'] = $phone;
        //$res = money_record::getList($where,$ktime,$gtime);
        $res = member::leftjoin('user','member.openid','=','user.openid')->where($where)->paginate(10);
        //var_dump($res);exit;
        if($res){
            foreach ($res as &$v){

            }
        }
        return view('admin.member.memberlist',[
            'list'=>$res,
            'phone'=>$phone,
            'status'=>$status,
            'user_type'=>$user_type,
            'ktime'=>$ktime,
            'gtime'=>$gtime,
        ]);
    }

       public function addBonus(Request $request){
           if($request->method()=="POST"){
               $phone = $request->input('phone');
               $bonus = $request->input('bonus');
               $via = $request->input('via');
               if(!$phone || !$bonus){
                   return fun_error_view(0, '缺少参数', 'addbonus');
               }
               $user_info = user::where(['phone'=>$phone])->first();
               if(!$user_info){
                   return fun_error_view(0, '未查询到用户信息！', 'addbonus');
               }
               //添加积分
               $openid = $user_info->openid;
               $member_info = get_member($user_info->openid);
               if($member_info){

                   $before_bonus = $member_info['bonus'];
                   $change_bonus = $bonus;
                   $after_bonus = $before_bonus+$change_bonus;
                   $status = $via;
                   $type = 1;
                   //更新用户的积分和皇冠
                   $crown_num = intval($after_bonus/10);
                   $res = member::where(['openid'=>$user_info->openid])->update(['bonus'=>$after_bonus,'crown_num'=>$crown_num]);
                   if(!$res){
                       return fun_error_view(0, '更新用户信息失败！', 'addbonus');
                   }
                   //调用微信的接口加积分
                   $record_bonus = sprintf("签到,增加积分%s", $bonus);
                   $result = WxSmallClient::updateMember($member_info['code'],$record_bonus,$change_bonus);
                   if($result->errcode==0){
                       add_bonus_record($openid,$before_bonus,$change_bonus,$after_bonus,$status,$type,2);
                   }else{
                       savelog('wx_bonus', '签到加积分'.$openid.'错误：'.$result->errmsg);
                   }
               }
               return fun_error_view(1, '添加积分成功', 'memberlist');
           }
           return view('admin/member/addbonus');
       }

    /**
     * [refunds 渠道商主动退款]
     * @param Request $request
     * @return
     */
    public function refunds(Request $request){
        respon(0,'该功能暂未开放');
        try{
            $data = $request->all();
            $order_num = isset($data['order_num'])?$data['order_num'] : '';
            $remarks = isset($data['remarks'])?$data['remarks'] : '';
            //$contact = isset($data['contact'])?$data['contact'] : '';
            $pwd = isset($data['password'])?$data['password'] : '';
            if(!check_pwd($pwd)) $this->respon(0, '密码错误');
            if(!$order_num){
                respon(0,'参数不能为空');
            }
            if(!$remarks){
                respon(0,'备注不能为空');
            }
            $order_info = order_info::getInfoByOrderNum($order_num);
            if(!$order_info){
                respon(0,'订单不存在');
            }
            if($order_info['dev_channel_id']==39){
                respon(0,'该类型不可退');
            }
            if($order_info['order_status'] != 2){
                respon(0,'订单类型错误');
            }
           
            $where = array(
                'id'=>$order_info['dev_channel_id'],
            );
            $channel_info = dev_channel::where($where)->first();

            if($channel_info['balance']<$order_info['pay_money']){
                respon(0,'渠道商账户余额不足');
            }
            DB::beginTransaction();
            //判断是微信还是支付宝
            if($order_info['pay_id']==1){
                $wx = new WxTransfer();
                $refund = [];
                $refund['orderNumber']=$order_info['order_number'];
                $refund['total_fee']=$order_info['pay_money'];
                if(isset($order_info['sub_mch_id']) && trim($order_info['sub_mch_id'])){
                    $refund['sub_mch_id'] = trim($order_info['sub_mch_id']);
                    $res = $wx->refund($refund,1);
                }else{
                    $res = $wx->refund($refund);
                }
            }else{
                $ali = new Alijssdk();
                $res = $ali->refund(['orderNumber'=>$order_info['order_number'],'total_fee'=>$order_info['pay_money']]);
            }
            if($res){
                if($remarks){
                    $des['remarks'] = $remarks;
                    //$des['contact'] = $contact;
                    $des = json_encode($des);
                    $res = order_sku::where(['order_id'=>$order_info['order_id']])->update(['description'=>$des]);
                    if(!$res){
                        throw new \Exception('退款失败!!');
                    }
                }
                //修改订单状态
                $result = order_info::editByOrderNumber($order_info['order_number'],['order_status'=>4, 'is_return'=>1]);
                if(!$result){
                    throw new \Exception('退款失败!');
                }
                //添加操作记录
                $res = channel_operating::addRecord($order_num,1);
                if(!$res){
                    throw new \Exception('退款失败');
                }
                //先写一条整体的收入记录
                $money_account = money_account::find(1);
                if(!$money_account){
                    $money_account = new money_account;
                    $money_account::create(['money'=>$order_info['pay_money']]);
                    $before_money = 0;
                    $after_money = $order_info['pay_money'];
                }else{
                    $money = $money_account->money;
                    if($money<=0){
                        respon(0,'账号金额错误！');
                    }
                    $before_money = $money;
                    $after_money = $money-$order_info['pay_money'];
                    $money_account->money = $after_money;
                    $money_account->save();
                }
                //添加记录
                $capital = array(
                    'user_id'=>0,
                    'user_type'=>4,
                    'type'=>2,//订单(退款)
                    'pay_type'=>$order_info['pay_id'],
                    'before_money'=>$before_money,//变更之前金额(账户余额)
                    'change_money'=>$order_info['pay_money'],//此次变更金额
                    'after_money'=>$after_money,//变更后金额
                    'status'=>3,//用户消费(收入)
                    'order_number'=>$order_info['order_number'],
                    'created_at'=>date('Y-m-d H:i:s',time()),
                );
                money_record::insertGetId($capital);
                /////todooo  ???????  平台未扣除余额
                //如果订单还没跑到渠道商的余额  直接总的减去 跟平台没关系
                if($order_info['is_settle']==0){
                    DB::commit();
                    respon(1,'退款成功!');
                }
                //计算三方的收益
                $total = sum_rate_money($order_info['pay_money'],$order_info['channel_rate'],$order_info['rate']);

                //平台抽成收益
                $plant_money = $total['plant_money'];
                if( $plant_money > 0)
                {
                    $operate = operates::where(['email' => 'yshow@e7124.com'])->first();
                    if($operate)
                    {
                        $operate = $operate->toArray();
                        $before_money = isset($operate['money'])?$operate['money']:0;
                        $after_money = $before_money - $plant_money;
                        operates::where('id',$operate['id'])->update(['money'=>$after_money]);
                        $capital = array(
                            'user_id'=>0,
                            'user_type'=>3,
                            'type'=>2,
                            'pay_type'=>$order_info['pay_id'],
                            'before_money'=>$before_money,
                            'change_money'=>$plant_money,
                            'after_money'=>$after_money,//变更后金额
                            'status'=>3,//用户消费(平台收入)
                            'order_number'=>$order_info['order_number']
                        );
                        money_record::insertGetId($capital);
                    }
                }

                $partner_money = $total['partner_money'];

                //判断 是否有 渠道商分成
                if(  ( $partner_money > 0 ) && isset( $order_info['partner_id'] ) &&  ( $order_info['partner_id'] > 0 )  )
                {
                    //合作伙伴的信息
                    $channel = dev_channel::getChannelInfo( ['id'=>$order_info['partner_id'] ] );
                    if( !empty($channel) )//合作伙伴存在并且分成比例大于0
                    {
                        $balance1 = $channel['balance'];
                        $data = array(
                            'balance'=>$balance1-$partner_money
                        );
                        dev_channel::updata( ['id'=>$order_info['partner_id'] ] , $data );
                        /*合作伙伴渠道账户添加资金流水*/
                        $capital = array(
                            'user_id'=>$channel['id'],
                            'user_type'=>2,
                            'type'=>2,
                            'pay_type'=>$order_info['pay_id'],
                            'before_money'=>$balance1 > 0 ? $balance1 : 0,//变更之前金额(账户余额)
                            'change_money'=>$partner_money,//此次变更金额
                            'after_money'=>$data['balance'],//变更后金额
                            'status'=>3,//用户消费(平台收入)
                            'order_number'=>$order_info['order_number'],
                            'created_at'=>date('Y-m-d H:i:s',time()),
                        );
                        money_record::insertGetId($capital);

                    }
                }

                //设备持有者资金变动
                $profits = $channel_info['balance'] - $total['channel_money'] ;
                $res = dev_channel::updata( $where,['balance'=>$profits] );
                if( !$res )
                {
                    $content = '修改渠道商余额错误'.$where['id'];
                    throw new \Exception($content);
                }
                /*渠道账户添加资金流水*/
                $capital = array(
                    'user_id'=>$channel_info['id'],
                    'user_type'=>2,
                    'type'=>2,
                    'pay_type'=>$order_info['pay_id'],
                    'before_money'=>$channel_info['balance'] > 0 ? $channel_info['balance'] : 0,//变更之前金额(账户余额)
                    'change_money'=>$total['channel_money'],//此次变更金额
                    'after_money'=>$profits,//变更后金额
                    'status'=>3,//用户消费(平台收入)
                    'order_number'=>$order_info['order_number'],
                    'created_at'=>date('Y-m-d H:i:s',time()),
                );
                money_record::insertGetId($capital);
                DB::commit();
                respon(1,'退款成功');
            }else{
                respon(1,'微信退款失败');
            }
        }catch (\Exception $ex){
            DB::rollback();
            respon(0, $ex->getMessage());
        }
    }



}
